package com.wtwd.wtwddevice.service.impl;


import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.extension.conditions.query.LambdaQueryChainWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.wtwd.device.constant.DeviceLoginEnum;
import com.wtwd.device.mqtentity.MessageBase;
import com.wtwd.device.protocol.AppProtocol;
import com.wtwd.wtwddevice.mapper.AppCommMapper;
import com.wtwd.wtwddevice.model.entity.AppComm;
import com.wtwd.wtwddevice.mq.PushAppMsgService;
import com.wtwd.wtwddevice.service.IAppCommService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Date;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author mjy
 * @since 2024-05-17
 */
@Slf4j
@Service
public class AppCommServiceImpl extends ServiceImpl<AppCommMapper, AppComm> implements IAppCommService {

    @Resource
    private AppCommMapper appCommMapper;

    @Resource
    private PushAppMsgService msgService;


    @Override
    public boolean insertOrUpdate(AppComm appComm) {
        if (appComm == null) {
            return false;
        }
        appComm.setCreateTime(new Date().getTime());
        appComm.setUpdateTime(new Date().getTime());
        return appCommMapper.insertOrUpdate(appComm);
    }

    @Override
    public boolean downLine(Long deviceId) {
        return appCommMapper.updateState(deviceId, DeviceLoginEnum.DEVICE_OFFLINE);
    }

    @Override
    public boolean pushDeviceState(Long deviceId, AppProtocol appProtocol) {
        AppComm appComm = getAppCommByDeviceId(deviceId);
        if (appComm == null||DeviceLoginEnum.DEVICE_OFFLINE==appComm.getStatus()) {
            log.error("推送异常{}-{} 设备未入库,或者app长连接管道未连接", appProtocol.getImei(),appProtocol.toString());
            return false;
        }
        msgService.pushToDevice(appComm.getHost(),
                MessageBase.builder()
                        .appProtocol(appProtocol)
                        .build());
        return true;
    }

    @Override
    public AppComm getAppCommByDeviceId(Long deviceId) {
        if (deviceId == null) {
            return null;
        }
        return new LambdaQueryChainWrapper<>(appCommMapper)
                .eq(AppComm::getDeviceId, deviceId)
                .one();
    }
}
